import { exec } from 'child_process';
import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';

const app = express();
const _rootDir = process.cwd()
// post 请求使用
app.use(bodyParser.urlencoded({ extended: true }));

// 静态目录配置
const staticPath = path.resolve(_rootDir, 'static');
app.use('/static', express.static(staticPath));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
  );
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200); // 更合理地处理 OPTIONS
  }
  next();
});



// 关机
function doShutDown () {
  return new Promise(function (resolve) {
    exec('shutdown /s /t 0', (err) => {
      if (err) {
        resolve(false)
      } else {
        resolve(true)
      }
    })
  })
}

app.get('/', async function (req, res) {
  res.json({
    code: 200,
    message: '服务工具运行中...',
  });
});
app.post('/shutdown', async function (req, res) {
  console.log("关机参数", req.body)
  const isSuccess = await doShutDown()
  const message = isSuccess ? '关机成功' : '关机失败！！！！！！！'
  res.end(message)
});

function server(port) {
  app.listen(port, function () {
    const message = `
      服务器地址: http://127.0.0.1:${port}
    `;
    console.log(message);
  });
}

server(10064)